<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>在拖放操作中使用 JSON</title>
    <style>
        [data-drop-target] {
            height: 400px;
            width: 200px;
            margin: 2px;
            background-color: gainsboro;
            float: left;
        }

        .drag-enter {
            border: 2px dashed #000;
        }

        .box {
            width: 200px;
            height: 200px;
        }

        .navy {
            background-color: navy;
        }

        .red {
            background-color: red;
        }
    </style>
</head>
<body>
<div data-drop-target="true">
    <div id="box1" draggable="true" class="box navy"></div>
    <div id="box2" draggable="true" class="box red"></div>
</div>
<div data-drop-target="true"></div>
<script>
    function handleDragStart(e) {
        var data = {
            elementId: this.id,
            message: 'You moved an element!'
        };
        e.dataTransfer.setData('text', JSON.stringify(data));
    }

    function handleDragEnterLeave(e) {
        if (e.type == 'dragenter') {
            this.classList.add('drag-enter');
        } else {
            this.className = ''
        }
    }

    function handleOverDrop(e) {
        e.preventDefault();
        if (e.type != 'drop') {
            return;
        }
        var json = e.dataTransfer.getData('text');
        var data = JSON.parse(json);
        var draggeElement = document.getElementById(data.elementId);
        if (draggeElement.parentNode == this) {
            this.className = '';
            return;
        }
        draggeElement.parentNode.removeChild(draggeElement);
        this.appendChild(draggeElement);
        this.className = '';
        alert(data.message);
    }

    var draggable = document.querySelectorAll('[draggable]');
    var targets = document.querySelectorAll('[data-drop-target]');

    for (var i = 0; i < draggable.length; i++) {
        draggable[i].addEventListener('dragstart',handleDragStart);
    }

    for (i = 0; i < targets.length; i++) {
        targets[i].addEventListener('dragenter',handleDragEnterLeave);
        targets[i].addEventListener('dragleave',handleDragEnterLeave);
        targets[i].addEventListener('dragover',handleOverDrop);
        targets[i].addEventListener('drop',handleOverDrop);
    }
</script>
</body>
</html>